from flask import Flask, request
from WXBizJsonMsgCrypt import WXBizJsonMsgCrypt
import json

# 配置参数
sToken = "D55BB6EBmT6MhE9IUB759"
sEncodingAESKey = "UIYgUyOHtAKGL45IMKTy3EW7JTzrSdqqaXTsM1bJ7oH"
sCorpID = "ww8ce04bff4de2a237"

# 创建 Flask 应用
app = Flask(__name__)
wxcpt = WXBizJsonMsgCrypt(sToken, sEncodingAESKey, sCorpID)

@app.route('/wework_callback', methods=['GET', 'POST'])
def wework_callback():
    if request.method == 'GET':
        # 验证 URL
        sVerifyMsgSig = request.args.get('msg_signature')
        sVerifyTimeStamp = request.args.get('timestamp')
        sVerifyNonce = request.args.get('nonce')
        sVerifyEchoStr = request.args.get('echostr')

        ret, sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr)
        if ret != 0:
            return f"ERR: VerifyURL ret: {ret}", 400
        return sEchoStr

    elif request.method == 'POST':
        # 处理加密消息
        sReqMsgSig = request.args.get('msg_signature')
        sReqTimeStamp = request.args.get('timestamp')
        sReqNonce = request.args.get('nonce')
        sReqData = request.get_data(as_text=True)

        ret, sMsg = wxcpt.DecryptMsg(sReqData, sReqMsgSig, sReqTimeStamp, sReqNonce)
        if ret != 0:
            return f"ERR: DecryptMsg ret: {ret}", 400

        # 解析解密后的消息
        try:
            msg = json.loads(sMsg)
            # 这里可以根据业务需求处理消息
            print("Received message:", msg)
            # 示例：回复消息
            sRespData = '{"ToUserName": "wx5823bf96d3bd56c7", "FromUserName": "mycreate", "CreateTime": 1409659813, "MsgType": "text", "Content": "hello", "MsgId": 4561255354251345929, "AgentID": 218}'
            ret, sEncryptMsg = wxcpt.EncryptMsg(sRespData, sReqNonce, sReqTimeStamp)
            if ret != 0:
                return f"ERR: EncryptMsg ret: {ret}", 400
            return sEncryptMsg, 200
        except json.JSONDecodeError:
            return "ERR: Invalid JSON format", 400

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)